//
//  LXJComposeWeiboPicturesView.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/4/6.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

let ComposeWeiboPicturesCellID = "ComposeWeiboPicturesCellID"

class LXJComposeWeiboPicturesView: UICollectionView {
    // MARK: 属性
    /// 用于存储用户选择的图片
    lazy var selecetedImagesArray: [UIImage] = [UIImage]()
    /// 点击加号摁扭的闭包
    var addPictureClosure: (() -> ())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        /// 界面加载
        setupUI()
    }
    
    /// 不使用 XIB 加载
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 设置背景颜色
        backgroundColor = UIColor.white
        /// 注册单元格
        self.register(LXJComposeWeiboPicturesViewCell.self, forCellWithReuseIdentifier: ComposeWeiboPicturesCellID)
        /// 设置数据源和代理对象
        self.dataSource = self
        self.delegate = self
        /// 当前视图默认隐藏
        isHidden = true
    }
    
    /// 添加图片
    func addSelecetedImages(image: UIImage) -> Void {
        /// 当照片数量大于9张的时候停止添加
        if selecetedImagesArray.count >= 9 {
            return
        }
        /// 往数组里添加元素
        selecetedImagesArray.append(image)
        /// 只要有图片就显示当前视图
        isHidden = false
        /// 刷新数据源
        reloadData()
    }
}

// MARK: 实现LXJComposeWeiboPicturesView的数据源方法
extension LXJComposeWeiboPicturesView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        /// 如果是第0张或者第9张的时候 按照实际显示
        if self.selecetedImagesArray.count == 0 || self.selecetedImagesArray.count == 9 {
            return self.selecetedImagesArray.count
        }else{/// 在1-8张之前多显示一个加号
            return self.selecetedImagesArray.count + 1
        }
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ComposeWeiboPicturesCellID, for: indexPath) as! LXJComposeWeiboPicturesViewCell
        /// 判断是否是最后一张图片
        if indexPath.item == self.selecetedImagesArray.count{
            cell.image = nil
        } else {
            /// 显示照片
            cell.image = self.selecetedImagesArray[indexPath.item]
            cell.indexPath = indexPath
            /// 执行删除闭包
            cell.deletePictureClosure = {[weak self] (index: Int) -> () in
                /// 根据当前索引删除图片
                self?.selecetedImagesArray.remove(at: index)
                /// 如果没有图片的饿时候隐藏当前视图
                if self?.selecetedImagesArray.count == 0 {
                    self?.isHidden = true
                }
                /// 删除数据后刷新数据源
                self?.reloadData()
            }
        }
        
        return cell
    }
    
    /// 判断是否点击的是最后一个 cell
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.selecetedImagesArray.count == indexPath.item {
            ///  执行添加图片的闭包
            addPictureClosure?()
        }
    }
}
// MARK: 自定义 cell
class LXJComposeWeiboPicturesViewCell: UICollectionViewCell{
    // MARK: 属性
    /// 数据源
    fileprivate var image: UIImage? {
        didSet{
            if image == nil {
                pictureView.image = UIImage(named: "compose_pic_add")
                /// 隐藏删除摁扭
                deleteButton.isHidden = true
            }else{
                pictureView.image = image
                /// 显示删除摁扭
                deleteButton.isHidden = false
            }
        }
    }
    
    /// 点击删除摁扭的时候的闭包回调
    var deletePictureClosure: ((Int) -> ())?
    /// 记录当前 cell 对应的 indexPath
    var indexPath: IndexPath?
    
    // MARK: 控件的懒加载
    /// 图片
    fileprivate lazy var pictureView: UIImageView = {
        let image = UIImageView()
        /// 设置缩放模式
        image.contentMode = .scaleAspectFill
        image.clipsToBounds = true
        return image
    }()
    /// 删除摁扭
    fileprivate lazy var deleteButton: UIButton = {
        let button = UIButton()
        /// 设置图片
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        /// 设置大小
        button.sizeToFit()
        /// 监听摁扭的点击事件
        button.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
        return button
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        /// 界面加载
        setupUI()
    }
    
    /// 不使用 XIB 加载
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 添加子控件
        contentView.addSubview(pictureView)
        contentView.addSubview(deleteButton)
        
        /// 自动布局
        pictureView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp.makeConstraints { (make) in
            make.top.equalTo(pictureView).offset(-2)
            make.trailing.equalTo(pictureView).offset(3)
        }
    }
    
    // MARK: 摁扭的点击事件
    @objc fileprivate func deleteAction() -> Void {
        /// 执行删除闭包
        deletePictureClosure?((indexPath?.item)!)
    }
}
